package com.pactera.asmp.server.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.pactera.asmp.server.common.annotations.JwtIgnore;
import com.pactera.asmp.server.common.constants.DeviceEnum;
import com.pactera.asmp.server.common.constants.PermissionCode;
import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.common.logprint.utils.CollectionUtils;
import com.pactera.asmp.server.entity.*;
import com.pactera.asmp.server.pojo.Role;
import com.pactera.asmp.server.pojo.User;
import com.pactera.asmp.server.service.AuthService;
import com.pactera.asmp.server.service.TokenServiceImpl;
import com.pactera.asmp.server.service.UserService;
import com.pactera.asmp.server.utils.Base64Util;
import com.pactera.asmp.server.utils.PageDataResult;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.Subject;
import org.crazycake.shiro.RedisCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description UserController
 * @auther: lzq
 * @date: 2019/7/29 11:10
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private AuthService authService;
    @Autowired
    private RedisCacheManager mRedisCacheManager;
    @Autowired
    private TokenServiceImpl mTokenService;
    @RequestMapping("/userList")
    public String toUserList() {
        return "/auth/userList";
    }

    /**
     * 分页查询用户列表
     *
     * @return ok/fail
     */

    /**
     * @api {post} /user/getUsers getUsers
     * @apiDescription 获取用户列表
     * @apiName getUsers
     * * @apiGroup User manage
     * @apiParam {Integer} page 第几页
     * @apiParam {Integer} limit 一页多少条数据
     * @apiParam {json} data 查询条件
     * @apiParamExample {json} Request-Example:
     * {
     * 	"page": 1,
     * 	"limit": 10,
     * 	"data": {
     * 		uname: null',
     * 		umobile: 'null',
     * 		insertTimeStart: 'null',
     * 		insertTimeEnd: 'null'
     * 		}
     * }
     * @apiSuccessExample Success-Response:
     * {
     * 	"totals": 11,
     * 	"code": 200,
     * 	"list": [{
     * 		id: 37,
     * 		username: 文方权,
     * 		mobile: 19916938871,
     * 		email: fangquan.wen@pactera.com,
     * 		password: null,
     * 		insertUid: 1,
     * 		insertTime: 2019-08-02 11:20:38.0,
     * 		updateTime: null,
     * 		isDel: false,
     * 		roleNames: 测试人员,
     * 		version: 0
     *        }]
     * }
     **/
    @RequestMapping(value = "/getUsers", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions({PermissionCode.USER_MANAGEMENT})
    public ResponseResult getUsers(@RequestBody UserSearchDTO userSearch) {
        int page = userSearch.getPage();
        int limit = userSearch.getLimit();
        logger.debug("分页查询用户列表！搜索条件：userSearch：" + userSearch + ",page:" + userSearch.getPage()
                + ",每页记录数量limit:" + userSearch.getLimit());
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        PageDataResult pdr = new PageDataResult();
        try {
            if (0 == page) {
                page = 1;
            }
            if (0 == limit) {
                limit = 10;
            }
            if(page < 0 || limit < 0) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("totals", 0);
                jsonObject.put("list", Lists.newArrayList());
                responseResult.setData(jsonObject);
                return responseResult;
            }
            // 获取用户和角色列表
            pdr = userService.getUsers(userSearch, page, limit);

                logger.debug("用户列表查询=pdr:" + pdr);
            if(CollectionUtils.isNotEmpty(pdr.getList())) {
                logger.debug("用户列表查询=pdr:" + pdr.getList().get(0));
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("totals", pdr.getTotals());
            jsonObject.put("list", pdr.getList());
            responseResult.setData(jsonObject);
            //responseResult.setData(JSON.toJSONStringWithDateFormat(pdr.getList(), "yyyy-MM-dd  HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
            responseResult = new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
            logger.error("用户列表查询异常！", e);
        }
        return responseResult;
    }


    /**
     * 设置用户[新增或更新]
     *
     * @return ok/fail
     */

    /**
     * @api {post} /user/setUser setUser
     * @apiDescription 设置用户[新增或更新]
     * @apiName setUser
     * @apiGroup User manage
     * @apiParam {String} roleIds 角色id
     * @apiParam {json} data 用户信息
     * @apiParamExample {json} Request-Example:
     * {
     * 	roleIds: 5
     * 	"data": {
     * 		id=37,
     * 		username=文方权,
     * 		mobile=19916938871,
     * 		email=fangquan.wen@pactera.com,
     * 		password=123456,
     * 		insertUid=null,
     * 		insertTime=null,
     * 		updateTime=null,
     * 		isDel=null, version=0
     * 		}
     * }
     * @apiSuccessExample Success-Response:
     * {
     * 	roleIds=5
     * 	{
     * 		id=37,
     * 		username=文方权,
     * 		mobile=19916938871,
     * 		email=fangquan.wen@pactera.com,
     * 		password=123456,
     * 		insertUid=1,
     * 		insertTime=null,
     * 		updateTime=null,
     * 		isDel=null,
     * 		version=0
     *        }
     * }
     **/

    @RequiresPermissions({PermissionCode.USER_MANAGEMENT})
    @RequestMapping(value = "/setUser", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult setUser(@RequestBody UserVO user) {
        ResponseResult responseResult;
        try {
            if (null == user) {
                logger.debug("设置用户[新增或更新]，结果=请您填写用户信息");
                responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
                return responseResult;
            }
//            if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getMobile())
//                    || StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getPassword())) {
//                logger.debug("设置用户[新增或更新]，结果=请您填写用户信息");
//                responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
//                return responseResult;
//            }
            logger.debug("设置用户[新增或更新]！user:" + user + ",roleIds:" + user.toString());
            if (null == user.getRoleIds() || user.getRoleIds().size() == 0) {
                logger.debug("置用户[新增或更新]，结果=请您给用户设置角色");
                responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
                return responseResult;
            }
            User existUser = (User) SecurityUtils.getSubject().getPrincipal();
            if (null == existUser) {
                logger.debug("置用户[新增或更新]，结果=您未登录或登录超时，请您登录后再试");
                responseResult = new ResponseResult(ResultCode.USER_NOT_LOGGED_IN);
                return responseResult;
            }
            user.setInsertUid(existUser.getId());
            // 设置用户[新增或更新]
            logger.info("设置用户[新增或更新]成功！user=" + user
                    + "，操作的用户ID=" + existUser.getId());
            responseResult = new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
            User userObject = new User();
            userObject.setUsername(user.getUsername());
            userObject.setId(user.getId());
            userObject.setPassword(user.getPassword());
            userObject.setEmail(user.getEmail());
            userObject.setMobile(user.getMobile());
            userObject.setVersion(user.getVersion());
            String result = userService.setUser(userObject, user.getRoleIds());
            if("ok".equals(result)){
                responseResult = new ResponseResult(ResultCode.SUCCESS);
            }else {
                responseResult.setMessage(result);
            }
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置用户[新增或更新]异常！", e);
            responseResult = new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
            return responseResult;
        }
    }

    /**
     * 删除用户
     *
     * @return ok/fail
     */

    /**
     * @api {post} /user/delUser delUser
     * @apiDescription 删除用户
     * @apiName delUser
     * @apiGroup User manage
     * @apiParam {int} id 用户id
     * @apiParam {int} version 角色id
     * @apiParamExample {json} Request-Example:
     * {
     * 	id: 38,
     * 	version: 0
     * }
     * @apiSuccessExample Success-Response:
     * {
     *  userId=38,
     *  操作用户id=1,
     *  version=0
     * }
     **/
    @RequiresPermissions({PermissionCode.USER_MANAGEMENT})
    @RequestMapping(value = "/delUser", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult delUser(@RequestBody JSONObject jsonParam, HttpServletRequest request) {
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        String msg;
        if (null == jsonParam.get("id") || null == jsonParam.get("version")) {
            logger.debug("删除用户，结果=请求参数有误，请您稍后再试");
            responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
            return responseResult;
        }
        try {
            Integer userId = Integer.valueOf(jsonParam.get("id").toString());
            Integer version = Integer.valueOf(jsonParam.get("version").toString());
            logger.debug("删除用户！id:" + userId + ",version:" +version);
            User existUser = (User) SecurityUtils.getSubject().getPrincipal();
            if (null == existUser) {
                logger.debug("删除用户，结果=您未登录或登录超时，请您登录后再试");
                responseResult = new ResponseResult(ResultCode.USER_NOT_LOGGED_IN);
                return responseResult;
            }
            // 删除用户
            msg = userService.setDelUser(userId, 1, existUser.getId(),version, request);
            logger.info("删除用户:" + msg + "！userId=" + userId + "，操作用户id:"
                    + existUser.getId() + ",version:" + version);
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除用户异常！", e);
            responseResult = new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
            return responseResult;
        }
    }

    /**
     * @api {post} /user/recoverUser recoverUser
     * @apiDescription 恢复用户
     * @apiName recoverUser
     * @apiGroup User manage
     * @apiParam {int} id 用户id
     * @apiParam {int} version 角色id
     * @apiParamExample {json} Request-Example:
     * {
     * 	id: 38,
     * 	version: 1
     * }
     * @apiSuccessExample Success-Response:
     * {
     *  userId=38,
     *  操作用户id=1,
     *  version=1
     * }
     **/
    @RequestMapping(value = "/recoverUser", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult recoverUser(@RequestBody JSONObject jsonParam, HttpServletRequest request) {
        ResponseResult responseResult;
        String msg = "";
        if (null == jsonParam.get("id") || null == jsonParam.get("version")) {
            responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
            return responseResult;
        }
        try {
            Integer userId = Integer.valueOf(jsonParam.get("id").toString());
            Integer version = Integer.valueOf(jsonParam.get("version").toString());
            logger.debug("恢复用户！id:" + userId + ",version:" + version);
            User existUser = (User) SecurityUtils.getSubject().getPrincipal();
            if (null == existUser) {
                responseResult = new ResponseResult(ResultCode.USER_NOT_LOGGED_IN);
                return responseResult;
            }
            // 删除用户
            msg = userService.setDelUser(userId, 0, existUser.getId(), version, request);
            logger.info("恢复用户【" + this.getClass().getName() + ".recoverUser】"
                    + msg + "。用户userId=" + userId + "，操作的用户ID=" + existUser.getId() + ",version:" + version);
            responseResult = new ResponseResult(ResultCode.SUCCESS);
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("恢复用户【" + this.getClass().getName()
                    + ".recoverUser】用户异常！", e);
            responseResult = new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
            return responseResult;
        }
    }

    /**
     * 查询用户数据
     *
     * @return map
     */
    /**
     * @api {post} /user/getUserAndRoles getUserAndRoles
     * @apiDescription 根据用户id查找用户角色
     * @apiName getUserAndRoles
     * @apiGroup User manage
     * @apiParam {int} id 用户id
     * @apiParamExample {json} Request-Example:
     * {
     * 	id: 38
     * }
     * @apiSuccessExample Success-Response:
     * {
         * id=38,
         * username=test,
         * mobile=13800000000,
         * email=***@QQ.com,
         * password=null,
         * insertUid=null,
         * insertTime=null,
         * updateTime=null,
         * isDel=false,
         * isJob=false,
         * userRoles=[UserRoleKey{userId=38, roleId=4}],
         * version=2
     * }
     **/
    @RequestMapping(value = "/getUserAndRoles", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult getUserAndRoles(@RequestBody JSONObject jsonParam) {
        Integer userId = Integer.valueOf(jsonParam.get("userId").toString());
        logger.debug("查询用户数据！id:" + userId);
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        Map<String, Object> map = new HashMap<>();
        try {
            if (null == userId) {
                logger.debug("查询用户数据==请求参数有误，请您稍后再试");
                map.put("msg", "请求参数有误，请您稍后再试");
                responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
                return responseResult;
            }
            // 查询用户
            UserRolesVO urvo = userService.getUserAndRoles(userId);
            logger.debug("查询用户数据！urvo=" + urvo);
            if (null != urvo) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("user", urvo);
                // 获取全部角色数据
                List<Role> roles = this.authService.getRoles();
                logger.debug("查询角色数据！roles=" + roles);
                if (null != roles && roles.size() > 0) {
                    jsonObject.put("roles", roles);
                }
            } else {
                map.put("msg", "查询用户信息有误，请您稍后再试");
                responseResult = new ResponseResult(ResultCode.RESULT_DATA_NONE);
                return responseResult;
            }
            logger.debug("查询用户数据成功！map=" + map);
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询用户数据异常！", e);
            responseResult = new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
            return responseResult;
        }
    }


    /**
     * 登录【使用shiro中自带的HashedCredentialsMatcher结合ehcache（记录输错次数）配置进行密码输错次数限制】
     * </br>缺陷是，无法友好的在后台提供解锁用户的功能，当然，可以直接提供一种解锁操作，清除ehcache缓存即可，不记录在用户表中；
     * </br>
     *
     * @param user
     * @param rememberMe
     * @return
     */
    /**
     * @api {post} /user/login login
     * @apiDescription 用户登录
     * @apiName login
     * @apiGroup Login
     * @apiParam {String} username 用户id
     * @apiParam {String} mobile 手机号
     * @apiParam {String} password 密码
     * @apiParam {Boolean} rememberMe 是否记住
     * @apiParamExample {json} Request-Example:
     * {
     *  UserDTO{
     *      id=null,
     *      username='lzqzzu',
     *      mobile='15921025861',
     *      email='null',
     *      password='654321',
     *      code='dddd'
     *  }，
     *  rememberMe：false
     * }
     * @apiSuccessExample Success-Response:
     * ResponseResult{
     *  code='1000',
     *  message='SUCCESS',
     *  obj=null
     * }
     **/
    @JwtIgnore
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult login(@RequestBody UserDTO user, @RequestParam(value = "rememberMe", required = false) boolean rememberMe) {
        logger.debug("用户登录，请求参数=user:" + user + "，是否记住我：" + rememberMe);
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        if (null == user) {
            logger.debug("用户登录，结果=responseResult:" + responseResult);
            return responseResult;
        }
        if (!validatorRequestParam(user, responseResult)) {
            logger.debug("用户登录，结果=responseResult:" + responseResult);
            return responseResult;
        }
        // 用户是否存在
        User existUser = this.userService.findUserByUserName(user.getUsername());
        if (existUser == null) {
            responseResult = new ResponseResult(ResultCode.USER_NOT_EXIST);
            logger.debug("用户登录，结果=responseResult:" + responseResult);
            return responseResult;
        }
        // 用户登录
        try {
            // 解密password
            user.setPassword(Base64Util.decodePwd(user.getPassword()));
            // 1、 封装用户名、密码、是否记住我到token令牌对象 [支持记住我]
            AuthenticationToken token = new UsernamePasswordToken(
                    user.getUsername(), DigestUtils.md5Hex(user.getPassword()),
                    rememberMe);
            // 2、 Subject调用login
            Subject subject = SecurityUtils.getSubject();
            // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            // 所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            logger.debug("用户登录，用户验证开始！user=" + user.getUsername());
            subject.login(token);

            //Todo Jwt toke Plan start
            User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
            List<Role> roles = authService.getRoleByUser(loginUser.getId());
            String userRoleId =StringUtils.EMPTY;
            userRoleId = String.valueOf(roles.get(0).getId());
            //JWT Token产生
            String tokenMessage = mTokenService.createToken(String.valueOf(loginUser.getId()), userRoleId, DeviceEnum.PC_BROWSER.getChannelId());
            logger.info("用户登录，用户验证通过！tokenMessage=" + tokenMessage);
            responseResult = new ResponseResult(ResultCode.SUCCESS);
            logger.info("用户登录，用户验证通过！user={} -- userId:{} -- roleId: {}" , user.getUsername(),loginUser.getId(),roles.get(0));
            JSONObject tokenJson = new JSONObject();
            tokenJson.put("token", tokenMessage);
            tokenJson.put("role",roles.get(0));
            tokenJson.put("userid", loginUser.getId());
            responseResult.setData(tokenJson);
            //Todo Jwt toke Plan end

        } catch (UnknownAccountException uae) {
            logger.error("用户登录，用户验证未通过：未知用户！user=" + user.getUsername(), uae);
            responseResult = new ResponseResult(ResultCode.USER_NOT_EXIST);
        } catch (IncorrectCredentialsException ice) {
            // 获取输错次数
            logger.error("用户登录，用户验证未通过：错误的凭证，密码输入错误！user=" + user.getUsername(),
                    ice);
            responseResult = new ResponseResult(ResultCode.USER_LOGIN_ERROR);
        } catch (LockedAccountException lae) {
            logger.error("用户登录，用户验证未通过：账户已锁定！user=" + user.getUsername(), lae);
            responseResult = new ResponseResult(ResultCode.USER_STATUE_LOCK);
        } catch (ExcessiveAttemptsException eae) {
            logger.error("用户登录，用户验证未通过：错误次数大于5次,账户已锁定！user=.getUsername()" + user, eae);
            responseResult = new ResponseResult(ResultCode.USER_STATUE_LOCK_MAX_TIP);
            //responseResult.setMessage("用户名或密码错误次数大于5次,账户已锁定!</br><span style='color:red;font-weight:bold; '>2分钟后可再次登录，或联系管理员解锁</span>");
            // 这里结合了，另一种密码输错限制的实现，基于redis或mysql的实现；也可以直接使用RetryLimitHashedCredentialsMatcher限制5次
        } catch (AuthenticationException ae) {
            // 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            logger.error("用户登录，用户验证未通过：认证异常，异常信息如下！user=" + user.getUsername(), ae);
            responseResult = new ResponseResult(ResultCode.USER_LOGIN_ERROR);
        } catch (Exception e) {
            logger.error("用户登录，用户验证未通过：操作异常，异常信息如下！user=" + user.getUsername(), e);
            responseResult = new ResponseResult(ResultCode.USER_LOGIN_ERROR);
        }
        Cache<String, AtomicInteger> passwordRetryCache = mRedisCacheManager.getCache("passwordRetryCache");
        if (null != passwordRetryCache) {
            int retryNum = (passwordRetryCache.get(existUser.getUsername()) == null ? 0
                    : passwordRetryCache.get(existUser.getUsername())).intValue();
            logger.debug("输错次数：" + retryNum);
            if (retryNum > 0 && retryNum < 6) {
                responseResult.setCode(ResultCode.USER_LOGIN_ERROR.code());
                responseResult.setMessage("用户名或密码错误" + retryNum + "次,再输错"
                        + (6 - retryNum) + "次账号将锁定");
            }
        }
        logger.debug("用户登录，user=" + user.getUsername() + ",登录结果=responseResult:"
                + responseResult);
        return responseResult;
    }


    /**
     * 修改密码
     *
     * @param pwd
     * @param isPwd
     * @return
     */
    /**
     * @api {post} /user/setPwd setPwd
     * @apiDescription 修改密码
     * @apiName setPwd
     * @apiGroup User manage
     * @apiParam {String} pwd 新密码
     * @apiParam {String} isPwd 确认密码
     * @apiParamExample {json} Request-Example:
     * {
     *  pwd:123456,
     * 	isPwd=123456
     * }
     * @apiSuccessExample Success-Response:
     * {
     *     ResponseResult{code='1000', message='SUCCESS', obj=null}
     * }
     **/
    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult setPwd(@RequestBody JSONObject jsonParam) {
        logger.debug("修改密码，请求参数=jsonParam:" + JSONObject.toJSONString(jsonParam));
        if(null == jsonParam.get("newPwd") || null == jsonParam.get("oldPwd")) {
            return new ResponseResult(ResultCode.PARAM_IS_BLANK);
        }
        String pwd = jsonParam.get("newPwd").toString();
        String oldPwd = jsonParam.get("oldPwd").toString();
        logger.debug("修改密码！pwd:" + pwd + ",oldPwd=" + oldPwd);
        ResponseResult responseResult;
        try {
            pwd = Base64Util.decodePwd(pwd);
            oldPwd = Base64Util.decodePwd(oldPwd);
            // 判断用户是否登录
            User existUser = (User) SecurityUtils.getSubject().getPrincipal();
            if (null == existUser) {
                responseResult = new ResponseResult(ResultCode.USER_NOT_LOGGED_IN);
                logger.debug("修改密码，结果=responseResult:" + responseResult);
                return responseResult;
            }
            if(!StringUtils.equals(DigestUtils.md5Hex(oldPwd), existUser.getPassword())) {
                responseResult = new ResponseResult(ResultCode.USER_PASSWORD_ERROR);
                logger.debug("修改密码，结果=responseResult:" + responseResult);
                return responseResult;
            }
            // 修改密码
            int num = this.userService.updatePwd(existUser.getId(),
                    DigestUtils.md5Hex(pwd));
            if (num != 1) {
                responseResult = new ResponseResult(ResultCode.USER_NOT_EXIST);
                logger.debug("修改密码失败，已经离职或该用户被删除！结果=responseResult:"
                        + responseResult);
                return responseResult;
            }
            responseResult = new ResponseResult(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseResult = new ResponseResult(ResultCode.FAIL);
            logger.error("修改密码异常！", e);
        }
        logger.debug("修改密码，结果=responseResult:" + responseResult);
        return responseResult;
    }

    /**
     * 登出
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public void logout(HttpServletRequest request) {
        userService.logout(request);
    }

    /**
     * 导出用户信息
     * 
     * @param userSearch
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public void exportUser(@RequestBody UserSearchDTO userSearch, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        logger.info("/user/export {}" + JSONObject.toJSONString(userSearch));
        userService.export(userSearch, response);
    }

    /**
     * @param obj
     * @param response
     * @return
     * @描述：校验请求参数getUsers
     */
    protected boolean validatorRequestParam(Object obj, ResponseResult response) {
        boolean flag = false;
		Validator validator = new Validator();
		List<ConstraintViolation> ret = validator.validate(obj);
		if (ret.size() > 0) {
			// 校验参数有误
			response.setCode(ResultCode.PARAM_IS_INVALID.code());
			response.setMessage(ret.get(0).getMessageTemplate());
		} else {
			flag = true;
		}
		return flag;
    }
}
